package com.mashibing.juc.c_008.interview;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName T04_WithoutVolatile
 * @Description 面试题
 * * * 实现一个容器，提供两个方法，add,size
 * * * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到达5的时候，线程2给出提示并结束
 * * * <p>
 * * * 案例四 合理使用wait notify
 * @Author xiongwei.wu
 * @Date 2021/7/13 9:16
 **/
public class T04_WithoutVolatile {
    volatile List lists = new ArrayList();

    private void addObj(Object object) {
        lists.add(object);
    }

    private int getSize() {
        return lists.size();
    }

    public static void main(String[] args) {
        T04_WithoutVolatile t = new T04_WithoutVolatile();

        final Object lock = new Object();

        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2 启动");
                if (t.getSize() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 结束");
                //t2线程结束后，要通知t1线程继续执行
                lock.notify();
            }
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 启动");
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {

                    t.addObj(new Object());
                    System.out.println("add: " + i);

                    if (t.getSize() == 5) {
                        lock.notify();
                        //释放锁，让t2得以执行
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("t1 结束");
        }, "t1").start();
    }
}
